/**
 * 
 * 
	new MaxTableSort({
		table: jQuery对象或dom对象,
		id_name: 表格id前缀,
		class_default: 'table_default', //默认排序的样式
		class_asc: 'table_asc',  		// 升序样式
		class_desc: 'table_desc',		// 降序样式
		
		rule_default: 0, //默认排序的样式
		rule_asc: 1,  		// 升序样式
		rule_desc: 2,		// 降序样式
		
		path: 图片路径,
		pic_default: 默认排序图片,
		pic_asc:升序图片,
		pic_desc:降序图片,
		sort_server:是否前端排序, 
								若为后端排序，在callback中写请求后台等回调；
								若为前端排序，则在初始时，根据表头列设置的排序规则自动排序（根据index的先后顺序，若没有设置排序规则则不进行初始化排序）。
		callback:function(sortOrder, sortField){} //传递出两个参数，sortOrder:排序规则，0：默认，1：升序，2：降序；sortField：当前排序的字段名；
	});
	
	需要排序的head部分的th,添加参数
	data-sort-order='yes' ： 启用该列的排序
	data-sort-rule="2" : 该列的排序规则
	data-sort-field='age' ： 该列的排序字段名
	data-sort-type='number' ： 该列的排序是否按数值。默认按字符串
 * 
 * 
 * */

;
(function(win, $) {
	var MaxTableSort = function(options) {
		MaxTableSort.CONFIG.ID += 1;
		this.initParm(options);
		this.initStyle();
		this.init();
		this.initOrderSort(this.table);
		this.events();
		return this;
	}
	MaxTableSort.CONFIG = {
		PIC_PATH: './',
		PIC_DEFAULT: 'table_default.png',
		PIC_ASC: 'table_asc.png',
		PIC_DESC: 'table_desc.png',
		CLASS_COMMON: '',
		CLASS_DEFAULT: 'table_default',
		CLASS_ASC: 'table_asc',
		CLASS_DESC: 'table_desc',
		RULE_DEFAULT: 0,
		RULE_ASC: 1,
		RULE_DESC: 2,
		ID_NAME: 'tableSort_',
		ID: 0,
		SORT_SERVER: false,
		CALLBACK: function(order, field){}
	}
	MaxTableSort.prototype.initParm = function(options) {
		this.table = options && options.table;
		if(!this.table) {
			alert('Error: Please specify a table object for the operation!');
			return;
		}
		//this.id_name = options && options.id_name || MaxTableSort.CONFIG.ID_NAME;
		this.id = $(this.table).attr('id') || (options && options.id_name || MaxTableSort.CONFIG.ID_NAME) + MaxTableSort.CONFIG.ID;
		this.path = options && options.path || MaxTableSort.CONFIG.PIC_PATH;
		
		this.class_common = options && options.class_common || MaxTableSort.CONFIG.CLASS_COMMON;
		this.class_default = options && options.class_default || MaxTableSort.CONFIG.CLASS_DEFAULT;
		this.class_asc = options && options.class_asc || MaxTableSort.CONFIG.CLASS_ASC;
		this.class_desc = options && options.class_desc || MaxTableSort.CONFIG.CLASS_DESC;

		this.rule_default = options && options.rule_default || MaxTableSort.CONFIG.RULE_DEFAULT;
		this.rule_asc = options && options.rule_asc || MaxTableSort.CONFIG.RULE_ASC;
		this.rule_desc = options && options.rule_desc || MaxTableSort.CONFIG.RULE_DESC;

		this.pic_default = options && options.pic_default || MaxTableSort.CONFIG.PIC_DEFAULT;
		this.pic_asc = options && options.pic_asc || MaxTableSort.CONFIG.PIC_ASC;
		this.pic_desc = options && options.pic_desc || MaxTableSort.CONFIG.PIC_DESC;
		this.sort_server = options && options.sort_server || MaxTableSort.CONFIG.SORT_SERVER;
		this.callback = options && options.callback || MaxTableSort.CONFIG.CALLBACK;
	}
	MaxTableSort.prototype.initStyle = function(cb) {
		var _this = this;
		var cssStyle = "<style type='text/css' id='tableSortSty'>" +
			".table_desc{display:inline-block;width:16px;height:16px;vertical-align:middle;background-image:url('" + _this.path + _this.pic_desc + "');background-size:16px 16px;}" +
			".table_asc{display:inline-block;width:16px;height:16px;vertical-align:middle;background-image:url('" + _this.path + _this.pic_asc + "');background-size:16px 16px;}" +
			".table_default{display:inline-block;width:16px;height:16px;vertical-align:middle;background-image:url('" + _this.path + _this.pic_default + "');background-size:16px 16px;}" +
			"</style>"

		var head = $(document).find("head")
		if(head.find("style#tableSortSty").length == 0) {
			var cssdom = head.find('style,link');
			if(cssdom.length) {
				cssdom.before(cssStyle);
			} else {
				head.append(cssStyle);
			}
		};
		cb && cb();
	}

	MaxTableSort.prototype.init = function() {
		this.table.attr('id', this.id);
		var _this = this;
		$('th[data-sort-order="yes"]').each(function() {
			var orderrule = $(this).data('sort-rule') || $(this).attr('data-sort-rule');
			var className = _this.class_default;
			if(orderrule == MaxTableSort.CONFIG.RULE_ASC) {
				className = _this.class_asc;
			} else if(orderrule == MaxTableSort.CONFIG.RULE_DESC) {
				className = _this.class_desc;
			}
			className = _this.class_common ? (className + ' ' + _this.class_common) : className;
			$(this).append('<span class="' + className + '"></span>');
			$(this).removeAttr('data-sort-order');
		});
	}
	
	MaxTableSort.prototype.initOrderSort = function(table) {
		var _this = this;
		if(_this.sort_server){
			return;
		}
		var rule = 0;
		var index = -1;
		var thDom = '';
		$(table).find('thead th').each(function(n){
			index = n;
			rule = _this.getAttr($(this), 'sort-rule'); 
			if( rule == MaxTableSort.CONFIG.RULE_ASC || rule == MaxTableSort.CONFIG.RULE_DESC){
				thDom = $(this);
				return false;
			}
		});
		if(thDom){
			new MaxTableSortOrder({
				table: _this.table,
				columnIndex: index,
				order: rule,
				orderType: _this.getAttr(thDom, 'sort-type')
			});
		}
	}
	
	MaxTableSort.prototype.getAttr = function(dom, attr) {
		return $(dom).data('attr') || $(dom).attr('data-' + attr);
	}
	
	MaxTableSort.prototype.events = function() {
		var _this = this;
		if(_this.sort_server){
			$('body').one('click', '#' + _this.id + ' .' + _this.class_default, function(e) {
				_this.orderSort($(this), MaxTableSort.CONFIG.RULE_DEFAULT);
			}).one('click', '#' + _this.id + ' .' + _this.class_asc, function(e) {
				_this.orderSort($(this), MaxTableSort.CONFIG.RULE_ASC);
			}).one('click', '#' + _this.id + ' .' + _this.class_desc, function(e) {
				_this.orderSort($(this), MaxTableSort.CONFIG.RULE_DESC);
			})
		}else{
			$('body').on('click', '#' + _this.id + ' .' + _this.class_default, function(e) {
				_this.orderSort($(this), MaxTableSort.CONFIG.RULE_DEFAULT);
			}).on('click', '#' + _this.id + ' .' + _this.class_asc, function(e) {
				_this.orderSort($(this), MaxTableSort.CONFIG.RULE_ASC);
			}).on('click', '#' + _this.id + ' .' + _this.class_desc, function(e) {
				_this.orderSort($(this), MaxTableSort.CONFIG.RULE_DESC);
			})
		}
	}

	MaxTableSort.prototype.orderSort = function(obj, order) {
		var _this = this;
		// 默认排序
		var table = $(obj).parents('table');
		var parTh = $(obj).parent('th');
		if(_this.sort_server){
			if(order == MaxTableSort.CONFIG.RULE_DEFAULT) {
				order = MaxTableSort.CONFIG.RULE_ASC;
			} else if(order == MaxTableSort.CONFIG.RULE_ASC) {
				order = MaxTableSort.CONFIG.RULE_DESC;
			} else if(order == MaxTableSort.CONFIG.RULE_DESC) {
				order = MaxTableSort.CONFIG.RULE_ASC;
			}
		}else{
			var index = parTh.index();
			var orderType = parTh.data('sort-type') || parTh.attr('data-sort-type');
			if(order == MaxTableSort.CONFIG.RULE_DEFAULT) {
				$(obj).removeClass(_this.class_default).addClass(_this.class_asc);
				order = MaxTableSort.CONFIG.RULE_ASC;
			} else if(order == MaxTableSort.CONFIG.RULE_ASC) {
				$(obj).removeClass(_this.class_asc).addClass(_this.class_desc);
				order = MaxTableSort.CONFIG.RULE_DESC;
			} else if(order == MaxTableSort.CONFIG.RULE_DESC) {
				$(obj).removeClass(_this.class_desc).addClass(_this.class_asc);
				order = MaxTableSort.CONFIG.RULE_ASC;
			}
			$(obj).parents('th').siblings().each(function() {
				$(this).find('.' + _this.class_asc).removeClass(_this.class_asc).addClass(_this.class_default);
				$(this).find('.' + _this.class_desc).removeClass(_this.class_desc).addClass(_this.class_default);
			});
			new MaxTableSortOrder({
				table: table,
				columnIndex: index,
				order: order,
				orderType: orderType
			});
		}
		
		_this.sortField = parTh.data('sort-field') || parTh.attr('data-sort-field');
		_this.sortOrder = order;
		_this.callback && _this.callback(_this.sortOrder, _this.sortField)
	}

	win.MaxTableSort = MaxTableSort;
	win.maxTableSort_InitParm = function(options) {
		MaxTableSort.CONFIG = {
			PIC_PATH: options.path || './',
			PIC_DEFAULT: options.pic_default || 'table_default.png',
			PIC_ASC: options.pic_asc || 'table_asc.png',
			PIC_DESC: options.pic_desc || 'table_desc.png',
			CLASS_COMMON: options.class_common || "",
			CLASS_DEFAULT: options.class_default || 'table_default',
			CLASS_ASC: options.class_asc || 'table_asc',
			CLASS_DESC: options.class_desc || 'table_desc',
			RULE_DEFAULT: options.rule_default || 0,
			RULE_ASC: options.rule_asc || 1,
			RULE_DESC: options.rule_desc || 2,
			ID_NAME: options.id_name || 'tableSort_',
			ID: options.id || 0,
			SORT_SERVER: options.sort_server || false,
			CALLBACK: options.callback || function(order, field){}
		}
	}
})(window, jQuery);

/**
 * 
 * 
	new MaxTableSortOrder({
		table: table, //表格jquery对象或dom对象
		columnIndex: index,  // 表格排序的列
		order: order,	// 排序规则：1:升序，2：降序
		orderType: orderType // 是否按数值排序，默认按字符串
	});
 * 
 * 
 * */

;
(function(win, $) {
	var MaxTableSortOrder = function(config) {
		this.table = $(config.table);
		this.columnIndex = config.columnIndex;
		this.order = config.order;
		this.orderType = config.orderType;
		this.init();
	};

	MaxTableSortOrder.ASC = 1; // 升序
	MaxTableSortOrder.DESC = 2; // 降序

	MaxTableSortOrder.prototype.init = function() {
		this.InitParm();
		this.sortColumn();
		this.changeTableTrs();
	}
	// 缓存需要使用的dom节点
	MaxTableSortOrder.prototype.InitParm = function() {
		this.tbody = this.table.find('tbody');
		this.trsArr = this.tbody.find('tr').clone();
		this.len = this.trsArr.length;
		this.sortArr = this.sortOrderArr();
	};

	// 
	MaxTableSortOrder.prototype.sortOrderArr = function() {
		var columnIndex = this.columnIndex;
		var arr = []
		this.table.find('tbody tr').each(function(n) {
			arr.push({
				text: $(this).find('td').eq(columnIndex).text(),
				index: n
			});
		});
		return arr;
	};

	MaxTableSortOrder.prototype.sortColumn = function() {
		var sortRule = this.order;
		var orderType = this.orderType;
		this.sortedArr = this.sortArr.concat();
		this.sortedArr.sort(function(a, b) {
			var a_Text = a.text;
			var b_Text = b.text;
			/*if(orderType == 'number'){
				if(sortRule == MaxTableSortOrder.ASC) {
					return a_Text - b_Text;
				} else if(sortRule == MaxTableSortOrder.DESC) {
					return b_Text - a_Text;
				}
			}else{*/
				if(sortRule == MaxTableSortOrder.ASC) {
					return a_Text.localeCompare(b_Text)
				} else if(sortRule == MaxTableSortOrder.DESC) {
					return b_Text.localeCompare(a_Text);
				}
			//}
		});
	};

	MaxTableSortOrder.prototype.changeTableTrs = function() {
		var trs = this.trsArr;
		var tbody = this.tbody;
		var sortedArr = this.sortedArr;
		this.tbody.html('');
		for(var i = 0; i < this.len; i++) {
			tbody.append(trs[sortedArr[i].index]);
		}
	};

	win.MaxTableSortOrder = MaxTableSortOrder;
})(window, jQuery)